package com.github.chirspan.xaas.log.util;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.chirspan.xaas.core.util.HeaderSecurityUtils;
import com.github.chirspan.xaas.log.model.ApiLog;
import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Objects;

/**
 * 系统日志工具类
 *
 * @author
 */
@UtilityClass
public class ApiLogUtils {
    public ApiLog getSysLog() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        ApiLog apiLog = new ApiLog();
        apiLog.setCreateBy(getUsername());
        apiLog.setType("0");
        apiLog.setRemoteAddr(ServletUtil.getClientIP(request));
        apiLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
        apiLog.setMethod(request.getMethod());
        apiLog.setUserAgent(request.getHeader("user-agent"));
        apiLog.setParams(getParams(request));
        apiLog.setServiceId(getClientId());
        return apiLog;
    }

    private String getParams(HttpServletRequest request) {
        String params = null;
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }

            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            params = jsonObject.toJSONString();
        } catch (Exception e) {

        }

        return params;

    }

    /**
     * 获取客户端
     *
     * @return clientId
     */
    private String getClientId() {
        return HeaderSecurityUtils.getClient();
    }

    /**
     * 获取用户名称
     *
     * @return username
     */
    private String getUsername() {
        return HeaderSecurityUtils.getUserName();
    }

}
